package com.cskaoyan.order.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.order.service.OrderPromoService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

@Component
public class PromoOrderConsumer {

    DefaultMQPushConsumer consumer;

    @Value("${rocketmq.address}")
    String rocketmqAddress;


    @Autowired
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        // 创建Consumer对象
       consumer = new DefaultMQPushConsumer("promo_order_consumer44");

       // 设置nameserver地址
        consumer.setNamesrvAddr(rocketmqAddress);

        // 设置消息监听器
        consumer.setMessageListener(new MessageListenerConcurrently() {
                    @Override
                    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                        // 获取消息中的数据
                        MessageExt message = msgs.get(0);
                        byte[] body = message.getBody();
                        String requestJson = new String(body, 0, body.length, Charset.forName("utf-8"));

                        CreateSeckillOrderRequest createSeckillOrderRequest
                                = JSON.parseObject(requestJson, CreateSeckillOrderRequest.class);

                        try {
                            orderPromoService.createPromoOrder(createSeckillOrderRequest);
                        } catch (Exception e) {
                            e.printStackTrace();
                            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                        }


                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                }
        );


        try {
            // 订阅主题
            consumer.subscribe("promo_order", "*");

            // 启动consumer
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
